import { device } from 'mx-libs'
import { userData } from '@/config/main'

function nativeAPIWrapper (native) {
  const api = native && native.api
  if (!api) throw new Error('nativeAPIWrapper api is null')

  getUserWrapper(api)

  return native
}

function getUserWrapper (api) {
  const getUser = api.getUser
  if (typeof getUser !== 'function') return

  api.getUser = function (...args) {
    return new Promise((resolve, reject) => {
      if (
        // 开发时 + 非美信环境 使用本地用户数据
        process.env.NODE_ENV === 'development' &&
        !device.isMission()
      ) {
        resolve(userData)
        return
      }

      let etag = new EndTag()

      const _resolve = (...agrs) => {
        if (etag) {
          etag.end()
          etag = null
          resolve(...agrs)
        }
      }

      const _reject = (...agrs) => {
        if (etag) {
          etag.end()
          etag = null
          reject(...agrs)
        }
      }

      getUser.apply(api, args).then(_resolve).catch(_reject);
      // 解决 getUser 在安卓环境下同时触发多次未响应的问题
      [200, 400, 600, 800, 1000].forEach(time => {
        etag.timers.push(setTimeout(() => {
          if (etag && !etag.isEnd) {
            console.warn('getUser timeout')
            getUser.apply(api, args).then(_resolve).catch(_reject)
          }
        }, time))
      })
    })
  }
}

class EndTag {
  constructor() {
    this.isEnd = false
  }

  get timers() {
    if (!this._timers) this._timers = []
    return this._timers
  }

  end() {
    this.isEnd = true
    this.timers.forEach(num => clearTimeout(num))
  }
}

export default nativeAPIWrapper
